﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Observer_Pattern
{
	class Program
	{
		/// <summary>
		/// 声明事件处理为委托
		/// </summary>
		public delegate void SubEventHander();

		/// <summary>
		/// 抽象主题类
		/// </summary>
		public abstract class Subject
		{
			public event SubEventHander subEventHander;
			public void FireAway()
			{
				if (subEventHander != null)
				{
					subEventHander();	
				}
			}
		}

		#region 主题类
		/// <summary>
		/// 主题信号源
		/// </summary>
		public class Dog:Subject
		{
			private string name;

			public Dog(string Name)
			{
				this.name = Name;
			}
			/// <summary>
			/// 信号发出
			/// </summary>
			public void Shout()
			{
				Console.WriteLine("我是"+name+"，发现一群老鼠汪汪汪,,,\n");
				this.FireAway();
			}
		}
		#endregion

		#region  单行为观察类
		/// <summary>
		/// 观察者的抽象类
		/// </summary>
		public abstract class Observer
		{
			/// <summary>
			/// 订阅主题消息
			/// </summary>
			/// <param name="sub"></param>
			public Observer(Subject sub)
			{
				sub.subEventHander += new SubEventHander(Response);
			}
			/// <summary>
			/// 观察者的行为实现
			/// 继承类可以重写自己的行为
			/// </summary>
			public abstract void Response();
		}

		/// <summary>
		/// 观察者
		/// </summary>
		public class Mouse:Observer
		{
			private string name;
			public Mouse(string Name, Subject sub): base(sub)
			{
				name = Name;
			}
		    public override void Response()
			{
				Console.WriteLine(name+"逃跑了,,,,");
			}
		}

		public class Monster : Observer
		{
			private string name;
			public Monster(string Name,Subject sub):base(sub)
			{
				name = Name;
			}
			public override void  Response()
			{
				Console.WriteLine();
				Console.WriteLine(name + "惊醒了,,,,");
			}
		}
		#endregion

		#region 多行为观察者
		public abstract class Observe2
		{
			public Observe2(Subject sub)
			{
				sub.subEventHander += new SubEventHander(Resonse1);
				sub.subEventHander += new SubEventHander(Resonse2);
			}
			public abstract void Resonse1();
			public abstract void Resonse2();
		}

		public class Cat : Observe2
		{ 
			private string name;
			public Cat(string Name, Subject sub): base(sub)
			{
				name = Name;
			}
			public override void Resonse1()
			{
				Console.WriteLine();
				Console.WriteLine(name+"喵喵喵,,,");
			}
			public override void Resonse2()
			{
				Console.WriteLine(name + "开始逮老鼠,,,");
			}
		}
		#endregion

		static void Main(string[] args)
		{
		    Dog dog = new Dog("小花狗");
			Mouse mouse1 = new Mouse("锦毛鼠", dog);
			Mouse mouse2 = new Mouse("小白鼠", dog);
			Monster monster = new Monster("女主人", dog);

			Cat cat = new Cat("小花猫",dog);

			dog.Shout();

			Console.ReadLine();
		}
	}
}
